﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.WebControls;
using EM.Repository.utility;
using System.Data;
using System.Text;
using System.Data.SqlClient;

namespace EMS.reports.income
{
    public partial class _default : System.Web.UI.Page
    {
        protected Conversion oC = new Conversion();
        protected DbHelper dsrv = new DbHelper();

        FillCombo fc = new FillCombo();

        int pageId = 20;

        protected void Page_Load(object sender, EventArgs e)
        {

            Authentication ua = new Authentication();
            ua.CheckRolePageAuthentication(pageId, Authentication.RedirectionURLTypes.LoginPage);

            if (!(Session["HISTORY"] as List<int>).Contains(pageId))
                (Session["HISTORY"] as List<int>).Add(pageId);

            if (!Page.IsPostBack)
            {
                fc.IncomeType(ddlINCOMETYPE, 0, true, (bool)HttpContext.Current.Session["UserIsAnAdmin"], Convert.ToInt32(Session["USERID"]));
                fc.User(ddlUSER, "0", true);
            }
        }

        private DataTable LoadData()
        {
            SqlCommand cmd = new SqlCommand();
            StringBuilder builder = new StringBuilder();
            builder.Append(@"SELECT INCOMEID, I.INCOMETYPEID, INCOMETYPENAME, CONVERT(NVARCHAR,INCOMEDATE,104) AS INCOMEDATE,
                            AMOUNT, U.USERDESC AS INCOMEUSER  FROM TBLINCOME I, TBLINCOMETYPE IT, TBLUSER U
                            WHERE I.INCOMETYPEID = IT.INCOMETYPEID AND I.INCOMEUSERID = U.USERID ");

            if (ddlINCOMETYPE.SelectedValue != "" && ddlINCOMETYPE.SelectedValue != "0")
            {
                builder.Append(" AND I.INCOMETYPEID = @INCOMETYPEID");
                cmd.Parameters.AddWithValue("@INCOMETYPEID", ddlINCOMETYPE.SelectedValue);
            }
            if (!(bool)HttpContext.Current.Session["UserIsAnAdmin"])
            {
                builder.Append(" AND I.INCOMEUSERID = @INCOMEUSERID");
                cmd.Parameters.AddWithValue("@INCOMEUSERID", Session["USERID"]);
            }
            else
            {
                if (ddlUSER.SelectedValue != "" && ddlUSER.SelectedValue != "0")
                {
                    builder.Append(" AND I.INCOMEUSERID = @INCOMEUSERID");
                    cmd.Parameters.AddWithValue("@INCOMEUSERID", ddlUSER.SelectedValue);
                }
            }

            if (rdpSTARTDATE.SelectedDate != rdpSTARTDATE.MinDate)
            {
                builder.Append(" AND I.INCOMEDATE >= @INCOMEDATESTART");
                cmd.Parameters.AddWithValue("@INCOMEDATESTART", rdpSTARTDATE.SelectedDate);
            }

            if (rdpENDDATE.SelectedDate != rdpENDDATE.SelectedDate)
            {
                builder.Append(" AND I.INCOMEDATE <= @INCOMEEND");
                cmd.Parameters.AddWithValue("@INCOMEEND", rdpENDDATE.SelectedDate);
            }

            cmd.CommandText = builder.ToString();


            DataTable dt = this.dsrv.GetDataTable(cmd, "INCOME");
            return dt;
        }

        private void BindGrid()
        {
            DataTable dt = new DataTable();
            dt = LoadData();
            rgMaster.DataSource = dt;

            rgMaster.MasterTableView.NoMasterRecordsText = "Kayıt bulunamadı.";
            rgMaster.StatusBarSettings.ReadyText = dt.Rows.Count + " adet kayıt bulundu.";

            rgMaster.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }


        double totalAmount = 0;
        double totalAmountTotal = 0;

        protected void rgMaster_ItemDataBound(object sender, GridItemEventArgs e)
        {
            Conversion oC = new Conversion();
            DataRowView drw = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
            {
                DataRowView row = e.Item.DataItem as DataRowView;

                double amount = 0;
                if (row["AMOUNT"].ToString() != "")
                    amount = Convert.ToDouble(row["AMOUNT"]);


                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Text = oC.CNumS2C(amount);

                totalAmount += amount;
            }
            else if (e.Item.ItemType == GridItemType.Footer)
            {

                DataTable dt = rgMaster.DataSource as DataTable;

                totalAmountTotal = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    totalAmountTotal += Convert.ToDouble(dt.Rows[i]["AMOUNT"]);
                }

                e.Item.Cells[rgMaster.Columns.FindByUniqueName("INCOMEDATE").OrderIndex].Text = "Sayfa Toplamı :<br />Genel Toplam :";
                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Style.Add("text-align", "right");
                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Text = oC.CNumS2C(totalAmount) + "<br /> " + oC.CNumS2C(totalAmountTotal);

                totalAmount = 0;
                totalAmountTotal = 0;
            }
        }

        protected void rgMaster_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
        {
            if (IsPostBack)
            {
                DataTable dt = new DataTable();
                dt = LoadData();
                rgMaster.DataSource = dt;

                rgMaster.MasterTableView.NoMasterRecordsText = "Kayıt bulunamadı.";
                rgMaster.StatusBarSettings.ReadyText = dt.Rows.Count + " adet kayıt bulundu.";
            }
        }

        protected void rgMaster_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Page" || e.CommandName == "Sort")
            {
                BindGrid();
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                rgMaster.ExportSettings.FileName = "Income";
                rgMaster.ExportSettings.ExportOnlyData = true;
                rgMaster.ExportSettings.IgnorePaging = true;
                rgMaster.ExportSettings.OpenInNewWindow = true;
                rgMaster.MasterTableView.ExportToExcel();
            }
            catch
            {
                ;
            }
        }
    }
}